﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;

namespace PrjSerails.SC
{
    public class MjjClient
    {
        TcpClient client;
        string serverIP;
        int serverPort;
        int maxDatagramSize = 20;
        byte[] m_receiveBuffer = new byte[2048 * 1024];

        private bool isConnedted;

        public bool IsConnedted
        {
            get { return client.Connected; }
        }


        public MjjClient(string ip, int port)
        {
            this.serverIP = ip;
            this.serverPort = port;
        }


        /// <summary>
        /// 连接
        /// </summary>
        /// <returns></returns>
        public bool Connect()
        {
            lock (this)
            {
                try
                {
                    client = new TcpClient(serverIP, serverPort);
                    client.ReceiveTimeout = 10 * 1000;
                    if (client.Connected)
                        return true;
                    else
                        return false;
                }
                catch (Exception ex)
                {
                    PrjSerails.UI.ShowMessageSinInfo si = new PrjSerails.UI.ShowMessageSinInfo(ex.Message);
                    si.Show();
                    return false;
                }
            }
        }


        public bool Tongfeng()
        {
            return SendOneDatagram(@"{cmd2#}");
        }

        public bool GuanJia()
        {
            return SendOneDatagram(@"{cmd3#}");
        }

        public bool PowerOn()
        {
            return SendOneDatagram(@"{cmd4#}");
        }

        public bool PowerOFF()
        {
            return SendOneDatagram(@"{cmd5#}");
        }

        public bool StopMove()
        {
            return SendOneDatagram(@"{cmd9#}");
        }

        /// <summary>
        /// 获取心跳数据
        /// </summary>
        /// <returns></returns>
        public bool GetData()
        {
            return SendOneDatagram(@"{cmd0#}");
 
        }

        /// <summary>
        /// 解森
        /// </summary>
        /// <returns></returns>
        public bool OpEnable()
        {
            return SendOneDatagram(@"{cmdb#}");
        }

        public bool OpenArchie(int lie, int jie, int cen, int ce)
        {
            return SendOneDatagram(@"cmda#" + lie.ToString() + "#" + jie.ToString() + "#" + cen.ToString() + "#" + ce.ToString() + "#");
        }


        public bool MoveLeft(int moveid)
        {
            return SendOneDatagram(@"{cmd7#"+moveid.ToString()+@"#1#}");
        }

        public bool MoveRight(int moveid)
        {
            return SendOneDatagram(@"{cmd7#" + moveid.ToString() + @"#0#}");
        }

        /// <summary>
        /// 关闭连接
        /// </summary>
        /// <returns></returns>
        public bool CloseConnect()
        {
            try
            {
                if (client.Connected)
                    client.Close();
                if (client.Connected == false)
                    return true;
                else
                    return false;
            }
            catch (Exception ex)
            {
                PrjSerails.UI.ShowMessageSinInfo si = new PrjSerails.UI.ShowMessageSinInfo(ex.Message);
                si.Show();
                return false;
            }
            finally
            {
                client = null;
            }
        }

        private bool SendOneDatagram(string tel)
        {
            bool result = false;
            int maxLength = maxDatagramSize * 1024;
            try
            {
                byte[] data = System.Text.Encoding.UTF8.GetBytes(tel);
                client.Client.Send(data);
                result = this.Receive(tel);
                return result;

            }
            catch (Exception err)
            {
                return false;

            }
        }

        private bool Receive(string tel)
        {

            try
            {
                int len = client.Client.Receive(m_receiveBuffer, 0, m_receiveBuffer.Length, SocketFlags.None);
                if (len > 4)
                {
                    string rcvStr = "";
                     byte[] receive = new byte[len];
                    Array.Copy(m_receiveBuffer, 0, receive, 0, len );
                    rcvStr = System.Text.Encoding.UTF8.GetString(receive);

                    ParaseTel(rcvStr);
                   
                }
                return false;
            }
            catch (Exception err)
            {
                return false;

            }
        }

        private void ParaseTel(string str)
        {
            string[] aStr = str.Split('#');
            for (int i = 0; i < aStr.Length; i++)
            {
                Global.mjjstate.MjjTem = Convert.ToInt32(aStr[0]);
                Global.mjjstate.MjjHum = Convert.ToDecimal(aStr[1]);
                Global.mjjstate.MjjFixId = Convert.ToInt32(aStr[2]);
                Global.mjjstate.MjjShelfNum = Convert.ToInt32(aStr[3]);
                if (aStr[4] == "0")
                    Global.mjjstate.IsPower = false;
                else
                    Global.mjjstate.IsPower = true;

                if (aStr[5] == "0")
                    Global.mjjstate.IsEnable = false;
                else
                    Global.mjjstate.IsEnable = true;
                if (aStr[8] == "0")
                    Global.mjjstate.IsLocked = false;
                else
                    Global.mjjstate.IsLocked = true;
                Global.mjjstate.ShelfPosition = aStr[9].ToString().Trim();
                   
                Global.mjjstate.Areaid = Convert.ToInt32(aStr[6]);
                Global.mjjstate.ShowTipInfo = aStr[7].ToString().Trim();
 
            }
        }

     

    }
}
